<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-input
                v-model="filters.wzm"
                placeholder="请输入物种名或拉丁名"
                clearable
              />
            </el-col>
            <el-col :span="10">
              <el-cascader
                v-model="selectedRegion"
                :options="regionOptions"
                :props="{ checkStrictly: true }"
                placeholder="选择行政区划"
                style="width: 300px"
                @change="handleRegionChange"
                clearable
                filterable
              />
            </el-col>
            <el-col :span="5">
              <div class="species-count">物种数量: {{ speciesCount }}</div>
            </el-col>
          </el-row>
        </div>
        <div class="center">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            :max-height="tableheight"
          >
            <el-table-column prop="id" label="id" width="75" />
            <el-table-column prop="wzm" label="物种名" show-overflow-tooltip />
            <el-table-column prop="ldm" label="拉丁名" show-overflow-tooltip />
            <el-table-column
              prop="xzqhname"
              label="行政区划"
              show-overflow-tooltip
            />
            <el-table-column prop="type" label="类型" show-overflow-tooltip />
            <el-table-column prop="jd" label="经度" show-overflow-tooltip />
            <el-table-column prop="wd" label="纬度" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
      <div class="bottom">
        <el-pagination
          :current-page="currentPage"
          background
          layout="total, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script>
import config from "@/config/config.js";

export default {
  name: "SpeciesDistribution",
  data() {
    return {
      tableheight: 300,
      tableData: [], // 原始数据
      paginatedData: [], // 当前页的数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数
      filters: {
        wzm: "",
        xzqhcode: "",
      },
      selectedRegion: [],
      regionOptions: config.xzqhArray,
      speciesCount: 0, // 物种数量
    };
  },

  created() {
    const height = window.innerHeight - 200;
    this.tableheight = height;
  },

  mounted() {
    this.fetchData();
  },

  watch: {
    // 当 filters 中的筛选条件变化时，重置当前页为 1，并更新分页数据
    filters: {
      handler() {
        this.currentPage = 1;
        this.updatePagination();
      },
      deep: true,
    },
  },

  computed: {
    // 计算筛选后的数据
    filteredData() {
      let data = this.tableData;

      // 物种名过滤
      if (this.filters.wzm) {
        const searchTerm = this.filters.wzm.toLowerCase();
        data = data.filter(
          (item) =>
            (item.wzm && item.wzm.toLowerCase().includes(searchTerm)) ||
            (item.ldm && item.ldm.toLowerCase().includes(searchTerm))
        );
      }

      // 行政区划过滤
      if (this.filters.xzqhcode) {
        data = data.filter((item) =>
          item.xzqhcode.startsWith(this.filters.xzqhcode)
        );
      }

      // 去重
      data = this.deduplicateDataByLdm(data);

      // 更新物种数量
      this.speciesCount = data.length;

      return data;
    },
  },

  methods: {
    async fetchData() {
      this.$api
        .getDistributedSpecies()
        .then((response) => {
          this.tableData = response.data.data;
          this.updatePagination();
        })
        .catch((error) => {
          console.error("失败:", error);
        });
    },

    deduplicateDataByLdm(data) {
      const seen = new Set();
      return data.filter((item) => {
        if (seen.has(item.ldm)) {
          return false;
        } else {
          seen.add(item.ldm);
          return true;
        }
      });
    },

    // 根据当前页码更新分页数据
    updatePagination() {
      const filteredData = this.filteredData;
      this.totalItems = filteredData.length;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = filteredData.slice(start, end);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.updatePagination();
    },

    handleRegionChange(value) {
      if (value.length > 0) {
        this.filters.xzqhcode = value[value.length - 1];
      } else {
        this.filters.xzqhcode = "";
      }
    },
  },
};
</script>

<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}
.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}
.species-count {
  font-weight: bold;
  line-height: 40px;
}
.bottom {
  text-align: right;
  padding-top: 20px;
}
.center {
  margin-top: 10px;
}
</style>
